# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.admin import widgets as admin_widgets
from .widgets import UEditorWidget, AdminUEditorWidget
import upyun
from django.core.files.storage import Storage, FileSystemStorage
from django.utils.encoding import filepath_to_uri
from django.conf import settings
import threading
import qiniu


class UEditorField(models.TextField,Storage):
    """
    百度HTML编辑器字段,初始化时，可以提供以下参数
        initial:初始内容
        toolbars:提供工具按钮列表,取值为列表，如['bold', 'italic'],取值为：mini,normal,full，代表小，一般，全部
        imagePath:图片上传的路径,如"images/",实现上传到"{{MEDIA_ROOT}}/images"文件夹
        filePath:附件上传的路径,如"files/",实现上传到"{{MEDIA_ROOT}}/files"文件夹
    """
    _instance_lock = threading.Lock()

    def __init__(self,verbose_name=None, width=600, height=300,upload_to='',
                 toolbars="full", imagePath="", filePath="",
                 upload_settings={}, settings={}, command=None,
                 event_handler=None, **kwargs):

        self.ueditor_settings = locals().copy()
        self.upload_to = upload_to

        if callable(upload_to):
            self.generate_filename = upload_to
        kwargs["verbose_name"] = verbose_name
        del self.ueditor_settings["self"], self.ueditor_settings[
            "kwargs"], self.ueditor_settings["verbose_name"]
        super(UEditorField, self).__init__(**kwargs)

    def formfield(self, **kwargs):
        defaults = {'widget': UEditorWidget(attrs=self.ueditor_settings)}
        defaults.update(kwargs)
        if defaults['widget'] == admin_widgets.AdminTextareaWidget:
            defaults['widget'] = AdminUEditorWidget(
                attrs=self.ueditor_settings)
        return super(UEditorField, self).formfield(**defaults)

    # # 使用 七牛云 上传图片
    # def qiniu_upload(key, localfile):
    #     q = qiniu.Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY)
    #     token = q.upload_token(settings.QINIU_BUCKET_NAME, key, 3600)
    #     ret, info = qiniu.put_file(token, key, localfile)
    #     if ret:
    #         return '{0}'.format(ret['key'])
    #     else:
    #         print '失败'
    #         return False
    #
    #
    # APPEND_SLASH = False
    # QINIU_ACCESS_KEY = 'ZgfxrmJdlZs4ozQ4K43ptH5efM9vpz3SV2FHZxFe'
    # QINIU_SECRET_KEY = '-XGP0RLvy16cUH1iZDBxvQdz_pjVwpvStACa-lgq'
    # QINIU_BUCKET_NAME = 'zhp_blog'
    # QINIU_DOMAIN = 'https://pp0jwjuOb.bkt.clouddn.com'
    # QINIU_USE_SSL = True
    # PREFIX_URL = 'http://'
    # APPEND_SLASH = settings.APPEND_SLASH
    # QINIU_ACCESS_KEY = settings.QINIU_ACCESS_KEY
    # QINIU_SECRET_KEY = settings.QINIU_SECRET_KEY
    # QINIU_BUCKET_NAME = settings.QINIU_BUCKET_NAME
    # QINIU_DOMAIN = settings.QINIU_DOMAIN
    # QINIU_USE_SSL = settings.QINIU_USE_SSL



    # 使用又拍云上传图片
    BUCKETNAME = settings.UPYUN_BUCKETNAME
    USERNAME = settings.UPYUN_USERNAME
    PASSWORD = settings.UPYUN_PASSWORD
    BASE_URL = settings.UPYUN_BASE_URL
    up = upyun.UpYun(BUCKETNAME, USERNAME, PASSWORD, timeout=30,
                     endpoint=upyun.ED_AUTO)

    def _save(self, name, content):
        if name[0] != '/':
            name = "/" + name
        try:
            res = self.up.put(name, content.read(), checksum=False)
            print res
        except Exception as e:
            raise
        return name

    def exists(self, name):
        try:
            self.up.getinfo(name)
        except Exception:
            return False
        return True

    def url(self, name):
        return self.BASE_URL + filepath_to_uri(name)

    @classmethod
    def simple_upload(cls, full_path_name, file_content):
        try:
            res = cls.up.put(full_path_name, file_content, checksum=False)
            print res
        except Exception as e:
            raise
        return cls.BASE_URL + filepath_to_uri(full_path_name)





# 以下支持south
try:
    from south.modelsinspector import add_introspection_rules
    add_introspection_rules([], ["^DjangoUeditor\.models\.UEditorField"])
except:
    pass
